﻿using System;
using System.Linq;
using Enyim.Caching;
using Ayatta.Contract;
using System.Web.Mvc;
using Web.Base.Security;
using Web.Base.Controllers;
using Web.Logistics.Models;
using Web.Base.ActionFilters;
using Web.Base.Components;
using Ayatta.Contract.Domain;
using Ayatta.Common.Extensions;
using Ayatta.Contract.Component;

namespace Web.Logistics.Controllers
{
    [SkAuthorize(UserRole.Seller)]
    public class HomeController : BaseController
    {
        public HomeController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient)
            : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Consign(string param)
        {
            var identity = User.Identity.Identity();
            var model = new HomeControllerModel.Index();
            var order = OrderService.GetOrder(param, identity.Id, true, true);
            if (order != null)
            {
                if (order.Status == OrderStatus.WaitSellerSend || order.Status == OrderStatus.SellerSendPart)
                {
                    var areas = GetAreas();
                    var addresses = GetUserAddresses(identity.Id).Where(o => o.Category != AddressCategory.Receive).ToList();

                    model.Areas = areas;
                    model.Order = order;
                    model.Addresses = addresses;
                    model.LogisticsCompanies = GetLogisticsCompanies();

                    var areaId = order.AreaId;
                    var p = areaId.Substring(0, 2);
                    var c = areaId.Substring(0, 4);

                    model.Province = new SelectList(areas.Where(o => o.Type == 1 && o.ParentId == "0"), "Id", "Name", p);
                    model.City = new SelectList(areas.Where(o => o.Type == 2 && o.ParentId == p), "Id", "Name", c);
                    model.District = new SelectList(areas.Where(o => o.Type == 3 && o.ParentId == c), "Id", "Name", areaId);
                    model.Shippings = new string[0];
                    if (order.Status == OrderStatus.SellerSendPart)
                    {
                        var temp = OrderService.GetSplitShippingOrderId(param);
                        if (!temp.IsNullOrEmpty())
                        {
                            model.Shippings = temp.Split(',');
                        }
                    }
                }
                else
                {
                    var url = WebSite.Seller + "/order/detail/" + order.Id;
                    return Redirect(url);
                }
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Consign(string param, string[] subId, int sendAddressId, int refundAddressId, string expressNo, string extra, UserAddress receiver)
        {
            var time = DateTime.Now;
            var identity = User.Identity.Identity();
            var result = new SkResult<object>();

            if (subId == null || subId.Length < 1)
            {
                result.Message = "请选择待发货的商品！";
                return Json(result);
            }
            var order = OrderService.GetOrder(param, identity.Id, true, true);
            if (order.Status == OrderStatus.WaitSellerSend || order.Status == OrderStatus.SellerSendPart)
            {

                var items =
                    order.OrderItems.Where(o => o.Status != OrderStatus.Canceled && o.Status != OrderStatus.Closed).
                        ToArray();
                var itemIds = items.Select(o => o.Id).ToArray();
                foreach (var id in subId)
                {
                    if (itemIds.Contains(id)) continue;
                    result.Data = id;
                    result.Message = "参数错误！";
                    return Json(result);
                }

                var shipping = new Shipping();
                var shippingExtra = new ShippingExtra();
                var shippingId = GenerateId('D', time, order.BuyerId, order.SellerId);

                shipping.Id = shippingId;
                shippingExtra.Id = shippingId;

                var areas = GetAreas();
                var tuple = GetAreaNames(order.AreaId, areas);

                shipping.OrderId = order.Id;

                shipping.ExpressNo = expressNo;
                shipping.Title = string.Empty;
                shipping.Summary = string.Empty;
                shipping.IsQuickCod = false;
                shipping.DeliveryStart = null;
                shipping.DeliveryEnd = null;
                shipping.FreightPayer = "seller";

                shipping.Receiver = receiver.Name;
                shipping.Company = string.Empty;
                shipping.Phone = receiver.Phone.EmptyIfNull();
                shipping.Mobile = receiver.Mobile.EmptyIfNull();
                shipping.AreaId = receiver.AreaId;
                shipping.Province = tuple.Item1;
                shipping.City = tuple.Item2;
                shipping.District = tuple.Item3;
                shipping.Address = receiver.Address;
                shipping.PostalCode = receiver.PostalCode;
                shipping.ShippingCompanyId = 0;
                shipping.ShippingCompany = string.Empty;
                shipping.BuyerId = order.BuyerId;
                shipping.BuyerNick = order.BuyerNick;
                shipping.SellerId = identity.Id;
                shipping.SellerNick = identity.NickName;
                shipping.Extra = extra.EmptyIfNull();
                shipping.Status = ShippingStatus.Created;
                shipping.ModifiedOn = time;
                shipping.CreatedBy = User.Identity.Name;
                shipping.CreatedOn = time;
                var addresses = GetUserAddresses(identity.Id);
                var sendAddress = addresses.FirstOrDefault(o => o.Id == sendAddressId);
                if (sendAddress != null)
                {
                    tuple = GetAreaNames(sendAddress.AreaId, areas);
                    shippingExtra.Sender = sendAddress.Name;
                    shippingExtra.Company = sendAddress.Company.EmptyIfNull();
                    shippingExtra.Phone = sendAddress.Phone.EmptyIfNull();
                    shippingExtra.Mobile = sendAddress.Mobile.EmptyIfNull();
                    shippingExtra.AreaId = sendAddress.AreaId;
                    shippingExtra.Province = tuple.Item1;
                    shippingExtra.City = tuple.Item2;
                    shippingExtra.District = tuple.Item3;
                    shippingExtra.Address = sendAddress.Address;
                    shippingExtra.PostalCode = sendAddress.PostalCode;
                }
                else
                {
                    result.Message = "发货地址不正确！";
                    return Json(result);
                }
                var refundAddress = addresses.FirstOrDefault(o => o.Id == refundAddressId);
                if (refundAddress != null)
                {
                    tuple = GetAreaNames(refundAddress.AreaId, areas);
                    shippingExtra.Refunder = refundAddress.Name;
                    shippingExtra.RefunderCompany = refundAddress.Company.EmptyIfNull();
                    shippingExtra.RefunderPhone = refundAddress.Phone.EmptyIfNull();
                    shippingExtra.RefunderMobile = refundAddress.Mobile.EmptyIfNull();
                    shippingExtra.RefunderAreaId = refundAddress.AreaId;
                    shippingExtra.RefunderProvince = tuple.Item1;
                    shippingExtra.RefunderCity = tuple.Item2;
                    shippingExtra.RefunderDistrict = tuple.Item3;
                    shippingExtra.RefunderAddress = refundAddress.Address;
                    shippingExtra.RefunderPostalCode = refundAddress.PostalCode;
                }
                else
                {
                    result.Message = "退货地址不正确！";
                    return Json(result);
                }
                shipping.ShippingExtra = shippingExtra;

                if (order.Status == OrderStatus.WaitSellerSend)
                {
                    if (items.Length == subId.Length)
                    {
                        shipping.OrderItemIds = itemIds.ToString(',');
                        order.Status = OrderStatus.WaitBuyerConfirm;
                    }
                    else
                    {
                        order.MultipleConsign = true;
                        shipping.OrderItemIds = subId.ToString(',');
                        order.Status = OrderStatus.SellerSendPart;
                    }
                }
                else if (order.Status == OrderStatus.SellerSendPart)
                {
                    var ids = OrderService.GetSplitShippingOrderId(order.Id).Split(',');
                    foreach (var id in subId)
                    {
                        if (!ids.Contains(id)) continue;
                        result.Data = id;
                        result.Message = "商品{0}已发货！";
                        return Json(result);
                    }
                    shipping.OrderItemIds = subId.ToString(',');
                    if (itemIds.Length == ids.Length + subId.Length)
                    {
                        order.Status = OrderStatus.WaitBuyerConfirm;
                    }

                }
                var status = OrderService.CreateShipping(shipping, order.MultipleConsign, identity.Id, order.Id,
                                                         order.Status, order.Version);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "创建物流订单异常！";
                }
            }
            else
            {
                result.Message = "订单状态错误！";
            }
            return Json(result);
        }
    }
}
